package com.ds.admin.listener;

import com.alibaba.fastjson2.JSONObject;
import com.ds.admin.event.User;
import com.ds.admin.event.UserEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @class: UserListener
 * @description:
 * @author: fs
 * @create: 2023/10/13 9:44
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class UserListener {

    private final RocketMQTemplate rocketMQTemplate;

    // @Async
    //@EventListener(UserEvent.class)
    //public void listener(UserEvent event) {
    //    User user = event.getUser();
    //    log.info("普通监听 = " + JSONUtil.toJsonStr(user));
    //}
    //
    //// @Async
    //// 事务监听 默认事务提交后执行 fallbackExecution 没有事务提交是否执行
    //@TransactionalEventListener(classes = UserEvent.class, fallbackExecution = true)
    //public void transactionalListener(UserEvent event) {
    //    User user = event.getUser();
    //    log.info("事务监听 = " + JSONUtil.toJsonStr(user));
    //}

    @Async
    @TransactionalEventListener(classes = UserEvent.class, fallbackExecution = true)
    public void sendMq(UserEvent event) {
        User user = event.getUser();
        MessageHeaderAccessor accessor = new MessageHeaderAccessor();
        Message<User> msg = MessageBuilder.withPayload(user).setHeaders(accessor).build();
        rocketMQTemplate.sendMessageInTransaction("test", msg, "123");
        log.info("发送给mq = " + JSONObject.toJSONString(user));
    }

}
